/**
 * @api post control.
 *
 * User: yunshengzhu
 * Date: 2020/12/4
 * Time: 下午3:05
 */
package control

import (
	"card-platform/config"
	"card-platform/model"
	"encoding/json"
	"encoding/xml"
	"errors"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"pkg/cfg"
	"pkg/utils"
	"time"
)

type Order struct {
}

// 每100张卡金额
const CardPrice = 28800

// swagger:operation POST /buyCard 订单类 buyCardReq
// ---
// summary: 购卡订单 buyCard.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/okResp"
func (a *Order) BuyCard(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := BuyCardReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}
	count := req.Num / 100
	num := count * 100
	if num != req.Num {
		return nil, config.ERR, errors.New("数量必须是100的整数倍")
	}

	order := model.OrderDb{}
	order.OrderNumber = "C" + utils.GetRandomStr(20)
	order.Num = req.Num
	order.UserId = userId
	order.Amount = uint64(count * CardPrice)
	order.PayAmount = order.Amount
	order.Typ = 1
	order.CreateTime = time.Now().Unix()
	order.Status = 0
	order.Mid = -1
	order.Desc = "购卡订单"

	//创建微信支付订单
	user, _ := model.GetUserId(userId)
	if len(user.OpenId) <= 0 {
		return nil, config.ERR, errors.New("用户数据异常")
	}

	wx := NewWeixinOrder()
	res, err := wx.MakeOrder(user.OpenId, order.OrderNumber, order.PayAmount, order.CreateTime)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	err = model.CreateOrder(order)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	addOrderLog(order.OrderNumber, "创建订单成功", "系统永不")

	resp := make(map[string]interface{})
	resp["orderNumber"] = order.OrderNumber
	resp["payAmount"] = order.PayAmount
	resp["wx"] = res
	resp["desc"] = order.Desc

	return resp, config.OK, nil
}

// 根据会员等级计算商品价格
func (a *Order) calculateProPrice(grade int, userId int64, price int64) int64 {
	if grade == 0 {
		return price
	}
	price = price * 80 / 100
	if price <= 0 {
		price = 1
	}
	return price
}

// 计算分利
//计算分利 铂金买东西分成给自己收30%，钻石卡分20%，平台5O%，钻石卡买自己分50%，平台50%
func divideCard(orderNumber string, mid, userId int64, payAmount int64, status int) (list []model.UserTransDb, err error) {
	//查询当前用户
	user, err := model.GetUserId(userId)
	if err != nil {
		cfg.LogErr("err:", err)
		return list, err
	}

	if user.Grade == 0 {
		platformAmount := payAmount
		list = append(list, model.UserTransDb{
			UserId:      -1,
			Amount:      platformAmount,
			Typ:         2,
			Desc:        "平台收益",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})
		return list, nil
	}

	platformAmount := (payAmount) / 2
	list = append(list, model.UserTransDb{
		UserId:      -1,
		Amount:      platformAmount,
		Typ:         2,
		Desc:        "平台收益",
		Status:      status,
		CreateTime:  time.Now().Unix(),
		OrderNumber: orderNumber,
	})

	switch user.Grade {
	case 1:
		userTwo, err := model.GetUserId(user.PUserId)
		if err != nil {
			cfg.LogErr("err:", err)
			return list, err
		}

		if userTwo.PUserId > 0 && userTwo.Grade == 2 {
			gradeAmount := (payAmount) * 30 / 100
			list = append(list, model.UserTransDb{
				UserId:      userTwo.UserId,
				Amount:      gradeAmount,
				Typ:         3,
				Desc:        "下级会员推广收益-铂金",
				Status:      status,
				CreateTime:  time.Now().Unix(),
				OrderNumber: orderNumber,
			})

			userThree, err := getUserUpLevel(userTwo.PUserId, 3)
			if err != nil {
				cfg.LogErr("err:", err)
				return list, err
			}

			if userThree.UserId <= 0 {
				cfg.LogInfo("userThree推荐用户不存在:", userThree)
				return list, errors.New("推荐用户不存在")
			}

			list = append(list, model.UserTransDb{
				UserId:      userThree.UserId,
				Amount:      payAmount - gradeAmount - platformAmount,
				Typ:         4,
				Desc:        "下下级会员推广收益-砖石",
				Status:      status,
				CreateTime:  time.Now().Unix(),
				OrderNumber: orderNumber,
			})
		} else {
			gradeAmount := payAmount - platformAmount
			list = append(list, model.UserTransDb{
				UserId:      userTwo.UserId,
				Amount:      gradeAmount,
				Typ:         3,
				Desc:        "下级会员推广收益-砖石",
				Status:      status,
				CreateTime:  time.Now().Unix(),
				OrderNumber: orderNumber,
			})
		}
		return list, err
	case 2:
		gradeAmount := payAmount * 30 / 100
		list = append(list, model.UserTransDb{
			UserId:      user.UserId,
			Amount:      gradeAmount,
			Typ:         3,
			Desc:        "会员返利",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})

		userThree, err := getUserUpLevel(user.PUserId, 3)
		if err != nil {
			cfg.LogErr("err:", err)
			return list, err
		}

		if userThree.UserId <= 0 {
			cfg.LogInfo("userThree推荐用户不存在:", userThree)
			return list, errors.New("推荐用户不存在")
		}

		list = append(list, model.UserTransDb{
			UserId:      userThree.UserId,
			Amount:      payAmount - gradeAmount - platformAmount,
			Typ:         4,
			Desc:        "推广收益",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})
		return list, nil
	case 3:
		list = append(list, model.UserTransDb{
			UserId:      user.UserId,
			Amount:      payAmount - platformAmount,
			Typ:         3,
			Desc:        "会员返利",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})
		return list, nil
	}
	return list, nil
}

// 计算分利
//计算分利 铂金买东西分成给自己收20%，钻石卡分30%，平台5O%，钻石卡买自己分50%，平台50%
// 商家90%,10%用于分利润
func divide(orderNumber string, mid, userId int64, payAmount int64, status int) (list []model.UserTransDb, err error) {
	merchantAmount := payAmount * 90 / 100
	merchant, err := model.GetMerchantMid(mid)
	if err != nil {
		cfg.LogErr("err:", err)
		return list, err
	}

	list = append(list, model.UserTransDb{
		UserId:      merchant.UserId,
		Amount:      merchantAmount,
		Typ:         1,
		Desc:        "售货收益",
		Status:      status,
		CreateTime:  time.Now().Unix(),
		OrderNumber: orderNumber,
	})

	//查询当前用户
	user, err := model.GetUserId(userId)
	if err != nil {
		cfg.LogErr("err:", err)
		return list, err
	}

	if user.Grade == 0 {
		platformAmount := payAmount - merchantAmount
		list = append(list, model.UserTransDb{
			UserId:      -1,
			Amount:      platformAmount,
			Typ:         2,
			Desc:        "平台收益",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})
		return list, nil
	}

	platformAmount := (payAmount - merchantAmount) / 2
	list = append(list, model.UserTransDb{
		UserId:      -1,
		Amount:      platformAmount,
		Typ:         2,
		Desc:        "平台收益",
		Status:      status,
		CreateTime:  time.Now().Unix(),
		OrderNumber: orderNumber,
	})

	switch user.Grade {
	case 1:
		userTwo, err := model.GetUserId(user.PUserId)
		if err != nil {
			cfg.LogErr("err:", err)
			return list, err
		}

		if userTwo.PUserId > 0 && userTwo.Grade == 2 {
			gradeAmount := (payAmount - merchantAmount) * 30 / 100
			list = append(list, model.UserTransDb{
				UserId:      userTwo.UserId,
				Amount:      gradeAmount,
				Typ:         3,
				Desc:        "下级会员推广收益",
				Status:      status,
				CreateTime:  time.Now().Unix(),
				OrderNumber: orderNumber,
			})

			userThree, err := getUserUpLevel(userTwo.PUserId, 3)
			if err != nil {
				cfg.LogErr("err:", err)
				return list, err
			}

			if userThree.UserId <= 0 {
				cfg.LogInfo("userThree推荐用户不存在:", userThree)
				return list, errors.New("推荐用户不存在")
			}

			list = append(list, model.UserTransDb{
				UserId:      userThree.UserId,
				Amount:      payAmount - merchantAmount - gradeAmount - platformAmount,
				Typ:         4,
				Desc:        "下下级会员推广收益",
				Status:      status,
				CreateTime:  time.Now().Unix(),
				OrderNumber: orderNumber,
			})
		} else {
			gradeAmount := payAmount - merchantAmount - platformAmount
			list = append(list, model.UserTransDb{
				UserId:      userTwo.UserId,
				Amount:      gradeAmount,
				Typ:         3,
				Desc:        "下级会员推广收益",
				Status:      status,
				CreateTime:  time.Now().Unix(),
				OrderNumber: orderNumber,
			})
		}
		return list, err
	case 2:
		gradeAmount := (payAmount - merchantAmount) * 30 / 100
		userThree, err := getUserUpLevel(user.PUserId, 3)
		if err != nil {
			cfg.LogErr("err:", err)
			return nil, err
		}

		list = append(list, model.UserTransDb{
			UserId:      user.UserId,
			Amount:      gradeAmount,
			Typ:         3,
			Desc:        "会员返利",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})

		if userThree.UserId <= 0 {
			cfg.LogInfo("userThree推荐用户不存在:", userThree)
			return list, errors.New("推荐用户不存在")
		}

		list = append(list, model.UserTransDb{
			UserId:      userThree.UserId,
			Amount:      payAmount - merchantAmount - gradeAmount - platformAmount,
			Typ:         4,
			Desc:        "推广收益",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})
		return list, nil
	case 3:
		list = append(list, model.UserTransDb{
			UserId:      user.UserId,
			Amount:      payAmount - merchantAmount - platformAmount,
			Typ:         3,
			Desc:        "会员收益",
			Status:      status,
			CreateTime:  time.Now().Unix(),
			OrderNumber: orderNumber,
		})
		return list, nil
	}
	return list, nil
}

func getUserUpLevel(pUserId int64, grade int) (obj model.UserDb, err error) {
	userUp, err := model.GetUserId(pUserId)
	if err != nil {
		cfg.LogErr("err:", err)
		return obj, err
	}
	if userUp.Grade == grade {
		return userUp, err
	}
	return getUserUpLevel(userUp.PUserId, grade)
}

// swagger:operation POST /buyPro 订单类 buyProReq
// ---
// summary: 购买商品 buyPro.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/okResp"
func (a *Order) BuyPro(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := BuyProReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	user, _ := model.GetUserId(userId)

	skuList := make([]int64, 0)

	for _, v := range req.SkuList {
		skuList = append(skuList, v.Sku)
	}

	if len(skuList) <= 0 {
		return nil, config.ERR, errors.New("商品信息不能为空")
	}

	proList, err := model.GetProSkuList(skuList)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if len(proList) != len(skuList) {
		return nil, config.ERR, errors.New("商品信息异常")
	}

	orderNumber := "P" + utils.GetRandomStr(20)

	var sumAmount, payAmount, num, mid int64

	online := false
	orderDetails := make([]model.OrderDetailDb, 0)
	for _, v := range proList {
		for _, v1 := range req.SkuList {
			if v.Sku == v1.Sku {
				/*if v.Stock < v1.Num {
					return nil, config.ERR, errors.New(fmt.Sprintf("商品%s库存不足,sku:%d", v.ProName, v.Sku))
				}*/
				if v.Online == 1 {
					online = true
				}
				mid = v.Mid
				num = num + v1.Num
				sumAmount = sumAmount + v.Price*v1.Num
				price := a.calculateProPrice(user.Grade, userId, v.Price)
				payAmount = payAmount + price*v1.Num
				orderDetails = append(orderDetails, model.OrderDetailDb{
					// 订单号
					OrderNumber: orderNumber,
					// 商品sku
					Sku: v.Sku,
					// 商品名称
					ProName: v.ProName,
					// 购买价格
					Price: price,
					// 商品原价
					OriginalPrice: v.Price,
					// 购买数量
					Num: v1.Num,
					// 是否线上 1线上 0线下
					Online: v.Online,
					// 图片列表
					Img: v.Img,
					// 商品内容
					Content: v.Content,
					// 商户Id
					Mid: v.Mid,
					// 订单时间
					CreateTime: time.Now().Unix(),
				})
			}
		}
	}

	if len(orderDetails) != len(req.SkuList) {
		return nil, config.ERR, errors.New("订单详情与商品信息不一致")
	}

	var logistics model.LogisticsDb

	logistics, _ = model.GetLogisticsUserIdAndId(userId, req.LogisticsId)
	if online && req.LogisticsId <= 0 {
		return nil, config.ERR, errors.New("请选择收货信息")
	}

	order := model.OrderDb{}
	order.OrderNumber = orderNumber
	order.Num = num
	order.UserId = userId
	order.Amount = uint64(sumAmount)
	order.PayAmount = uint64(payAmount)
	if online {
		order.Typ = 3
	} else {
		order.Typ = 2
	}

	order.CreateTime = time.Now().Unix()
	order.Status = 0
	order.Desc = "商品订单"
	order.Name = logistics.Name
	order.Address = logistics.Address
	order.ProvinceName = logistics.ProvinceName
	order.CityName = logistics.CityName
	order.CountyName = logistics.CountyName
	order.TownName = logistics.TownName
	order.Mobile = logistics.Mobile
	order.Mid = mid

	//创建微信支付订单
	user, _ = model.GetUserId(userId)
	if len(user.OpenId) <= 0 {
		return nil, config.ERR, errors.New("用户数据异常")
	}

	wx := NewWeixinOrder()
	res, err := wx.MakeOrder(user.OpenId, order.OrderNumber, order.PayAmount, order.CreateTime)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	resBytes, _ := json.Marshal(res)
	order.Wx = string(resBytes)

	err = model.CreateProOrder(order, orderDetails)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	addOrderLog(order.OrderNumber, "创建订单成功", "用户下单")
	resp := make(map[string]interface{})
	resp["orderNumber"] = order.OrderNumber
	resp["payAmount"] = order.PayAmount
	resp["wx"] = res
	resp["desc"] = order.Desc
	return resp, config.OK, nil
}

// swagger:operation POST /prepositionBuyPro 订单类 prepositionBuyProReq
// ---
// summary: 下单前置接口 prepositionBuyPro.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/prepositionBuyProResp"
func (a *Order) PrepositionBuyPro(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := PrepositionBuyProReq{}
	resp := PrepositionBuyProResp{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	user, _ := model.GetUserId(userId)

	skuList := make([]int64, 0)
	for _, v := range req.SkuList {
		skuList = append(skuList, v.Sku)
	}

	if len(skuList) <= 0 {
		return nil, config.ERR, errors.New("商品信息不能为空")
	}

	proList, err := model.GetProSkuList(skuList)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR, err
	}

	if len(proList) != len(skuList) {
		return nil, config.ERR, errors.New("商品信息异常")
	}

	orderNumber := "P" + utils.GetRandomStr(20)

	var sumAmount, payAmount, num int64

	orderDetails := make([]model.OrderDetailDb, 0)
	for _, v := range proList {
		for _, v1 := range req.SkuList {
			if v.Sku == v1.Sku {
				/*if v.Sold < v1.Num {
					return nil, config.ERR, errors.New(fmt.Sprint("商品%s库存不足,sku:%d", v.ProName, v.Sku))
				}*/
				num = num + v1.Num
				sumAmount = sumAmount + v.Price*v1.Num
				price := a.calculateProPrice(user.Grade, userId, v.Price)
				payAmount = payAmount + price*v1.Num
				imgs := make([]string, 0)

				json.Unmarshal([]byte(v.Img), &imgs)

				orderDetails = append(orderDetails, model.OrderDetailDb{
					// 订单号
					OrderNumber: orderNumber,
					// 商品sku
					Sku: v.Sku,
					// 商品名称
					ProName: v.ProName,
					// 购买价格
					Price: price,
					// 商品原价
					OriginalPrice: v.Price,
					// 购买数量
					Num: v1.Num,
					// 是否线上 1线上 0线下
					Online: v.Online,
					// 图片列表
					Img: v.Img,
					// 图片列表
					Imgs: imgs,
					// 商品内容
					Content: v.Content,
					// 商户Id
					Mid: v.Mid,
					// 订单时间
					CreateTime: time.Now().Unix(),
				})
			}
		}
	}

	if len(orderDetails) != len(req.SkuList) {
		return nil, config.ERR, errors.New("订单详情与商品信息不一致")
	}

	logistics, _ := model.GetLogisticsUserIdMain(userId)

	resp.LogisticsId = logistics.LogisticsId
	resp.Logistics = logistics
	resp.Amount = sumAmount
	resp.PayAmount = payAmount
	resp.ProList = orderDetails
	return resp, config.OK, nil
}

type WxPay struct {
	Sign      string `json:"sign"`
	PrepayId  string `json:"prepayid"`
	PartnerId string `json:"partnerid"`
	NonceStr  string `json:"noncestr"`
	Package   string `json:"package"`
	TimeStamp int64  `json:"timestamp"`
	AppID     string `json:"appid"`
	SignType  string `json:"signType"`
}

// swagger:operation POST /getOrderPay 订单类 getOrderPayReq
// ---
// summary: 获取订单支付信息 getOrderPay.
// description: .
//// responses:
////   "200":
////     "$ref": "#/responses/prepositionBuyProResp"
func (a *Order) GetOrderPay(userId int64, data []byte, param Param) (out interface{}, code int, err error) {
	req := GetOrderPayReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		cfg.LogErr("err:", err)
		return nil, config.ERR_JSON, err
	}

	obj, _ := model.GetOrderNumber(req.OrderNumber)

	if obj.Status != 0 {
		return nil, config.ERR, errors.New("订单状态不允许支付")
	}

	if len(obj.OrderNumber) <= 0 {
		cfg.LogErr("订单号不存在:", req.OrderNumber)
		return nil, config.ERR, errors.New("订单不存在")
	}

	//创建微信支付订单
	user, _ := model.GetUserId(userId)
	if len(user.OpenId) <= 0 {
		return nil, config.ERR, errors.New("用户数据异常")
	}

	if len(obj.Wx) <= 0 {
		//
		wx := NewWeixinOrder()
		res, err := wx.MakeOrder(user.OpenId, obj.OrderNumber, obj.PayAmount, time.Now().Unix())
		if err != nil {
			cfg.LogErr("err:", err)
			return nil, config.ERR, err
		}

		wxBytes, _ := json.Marshal(res)
		//更新微信支付参数
		model.UpdateOrderWx(obj.OrderNumber, string(wxBytes))
		return res, config.OK, nil
	}

	res := WxPay{}
	err = json.Unmarshal([]byte(obj.Wx), &res)
	if err != nil {
		cfg.LogErr("err:", err)
	}
	return res, config.OK, nil
}

func WxCallback(c *gin.Context) {
	bytes, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		cfg.LogErr("err:", err)
		return
	}

	cfg.LogInfo("微信回调数据:", string(bytes))
	callBackResult := CallbackResult{}
	err = xml.Unmarshal(bytes, &callBackResult)
	if err != nil {
		cfg.LogErr("err:", err)
		return
	}

	if callBackResult.ReturnCode != "SUCCESS" || callBackResult.ResultCode != "SUCCESS" {
		return
	}

	//执行订单查询操作

	wx := WeixinPay{}

	refundOrder, err := wx.QueryOrder(callBackResult.OutTradeNo)
	if err != nil {
		cfg.LogErr("err:", err)
		return
	}

	if refundOrder.ReturnCode != "SUCCESS" || refundOrder.ResultCode != "SUCCESS" {
		cfg.LogErr("订单状态异常:", refundOrder)
		return
	}

	order, err := model.GetOrderNumber(refundOrder.OutTradeNo)

	if order.Status != 0 {
		cfg.LogErr("订单状态异常,回调处理失败", order)
		return
	}

	order.PayStatus = 1
	order.PayTime = time.Now().Unix()
	switch order.Typ {
	case 1:
		order.Status = 3
	case 2:
		order.Status = 2
	case 3:
		order.Status = 1
	default:
		order.Status = 1
	}

	err = model.UpdateOrder(order)
	if err != nil {
		cfg.LogErr("err:", err)
		return
	}

	// 买卡订单
	if order.Typ == 1 {
		// 计算订单利润
		trans, err := divideCard(order.OrderNumber, order.Mid, order.UserId, int64(order.PayAmount), 2)
		if err != nil {
			cfg.LogErr("err:", err)
		}
		if len(trans) > 0 {
			err = model.CreateUserTransList(trans)
			if err != nil {
				cfg.LogErr("err:", err)
			}
			//分配利润
			model.RemitAmount(order.OrderNumber)
		}
		go createCard(order.OrderNumber)
	} else if order.Typ == 2 || order.Typ == 3 {
		//更新已售数据
		model.UpdateProStock(order.OrderNumber)
		// 计算订单利润
		trans, err := divide(order.OrderNumber, order.Mid, order.UserId, int64(order.PayAmount), 2)
		if err != nil {
			cfg.LogErr("err:", err)
		}
		if len(trans) > 0 {
			err = model.CreateUserTransList(trans)
			if err != nil {
				cfg.LogErr("err:", err)
			}
		}
	}

	addOrderLog(refundOrder.OutTradeNo, "微信支付回调成功,修改订单支付状态为已支付,修改订单状态为预定成功", "系统")
	str := `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`
	c.Writer.WriteString(str)
}

func WxRefundCallback(c *gin.Context) {
	bytes, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		cfg.LogErr("err:", err)
		return
	}

	cfg.LogInfo("微信退款回调数据:", string(bytes))
	callBackResult := CallbackResult{}
	err = xml.Unmarshal(bytes, &callBackResult)
	if err != nil {
		cfg.LogErr("err:", err)
		return
	}

	if callBackResult.ReturnCode != "SUCCESS" || callBackResult.ResultCode != "SUCCESS" {
		return
	}
	str := `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`
	c.Writer.WriteString(str)
}

func addOrderLog(orderNumber, content, operator string) error {
	log := model.OrderLogModel{}
	log.OrderNumber = orderNumber
	log.CreateTime = time.Now().Unix()
	log.Content = content
	log.Operator = operator
	err := model.AddOrderLog(log)
	if err != nil {
		cfg.LogErr("err:", err)
	}
	return err
}
